package com.hqyj.bigdata.hiveproject.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.hqyj.bigdata.hiveproject.entity.Users;
import com.hqyj.bigdata.hiveproject.json.R;
import com.hqyj.bigdata.hiveproject.service.UsersService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("users")
public class UsersController extends BaseController {

    @Resource
    private UsersService usersService;

    @PostMapping("/")
    public R reg(@RequestBody Users u){
        try{
            if(usersService.reg(u)){
                return R.success("恭喜您，注册成功！");
            }
            return R.fail("很遗憾，注册失败！");
        }catch (Exception ex){
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @GetMapping("auth")
    public R login(@RequestParam(value = "identify",required = true) String identify, @RequestParam(value = "password",required = true) String password,@RequestParam(value = "token",required = true) String token, @RequestParam(value = "code",required = true) String code){
        try{
            //必须先检查用户输入的验证码
            if(!redisUtil.hasKey(token)){
                return R.fail("验证码验证失败！");
            }

            String sessionRadomCode = (String) redisUtil.get(token);
            if(!code.equalsIgnoreCase(sessionRadomCode)){
                return R.fail("验证码验证失败！");
            }

            Users loginSuccessUser = usersService.login(identify,password);
            if(loginSuccessUser!=null){
                //如果进到这里，说明用户登录成功
                StpUtil.login(loginSuccessUser.getId());
                loginSuccessUser.setPassword(""); //把用户密码置空，因为密码返回到前端不安全的。
                return R.success("登录成功！",loginSuccessUser);
            }
            return R.fail("登录失败，请检查用户名或者密码是否正确！");
        }catch (Exception ex){
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @GetMapping("/isLogin")
    //判断当前用户是否已经登录
    public R isLogin(){
        try{
            boolean flag = StpUtil.isLogin();
            return R.success("查询用户登录状态成功！",flag);
        }catch (Exception ex){
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }

    @GetMapping("logout")
    public R logout(){
        try{
            StpUtil.logout();
            return R.success("注销成功！");

        }catch(Exception ex){
            ex.printStackTrace();
            return R.error("程序出现异常！");
        }
    }
}
